package com.qingcloud.adminbackend.entity.common;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Getter
@Setter
@Accessors(chain = true)
@ToString
public class CascadeTree implements Serializable {

    @ApiModelProperty(value = "树节点值", example = "100")
    private String value;

    @ApiModelProperty(value = "父节点", example = "1", hidden = true)
    transient private String parentValue;

    @ApiModelProperty(value = "节点名称", example = "100")
    private String label;

    @ApiModelProperty(value = "子节点")
    private List<CascadeTree> children;

    /**
     * 转成级联的数据结构
     */
    public static List<CascadeTree> convertTree(List<CascadeTree> treeList) {
        //按父级分组
        Map<String, List<CascadeTree>> childrenMap = treeList.stream().filter(it -> StrUtil.isNotBlank(it.getParentValue()))
                .collect(Collectors.groupingBy(CascadeTree::getParentValue));
        //设置子集合
        for (CascadeTree cascadeTree : treeList) {
            cascadeTree.setChildren(childrenMap.get(cascadeTree.getValue()));
        }
        List<CascadeTree> firstList = treeList.stream().filter(it -> Objects.isNull(it.getParentValue()))
                .collect(Collectors.toList());
        return firstList;
    }

}
